import os
os.environ["QT_API"] = "pyqt5"

import sys
from PyQt5.QtWidgets import QWidget, QApplication, QVBoxLayout, QPushButton
from PyQt5.QtCore import QThread, pyqtSignal
from pyqtgraph import PlotWidget
import numpy as np

class TimeCanvas:
    """
    定义时域图
    """
    def __init__(self):
        # 窗口
        self.widget = QWidget()
        # 按钮
        self.button = QPushButton("&Start")
        # 图控件
        self.pw = PlotWidget()
        self.pw.setAutoPan(x=True, y=True)
        self.plot = self.pw.plot()
        # 队列
        self.x_data = np.array([])
        self.y_data = np.array([])
        # 布局
        self.layout = QVBoxLayout()
        # 将控件的设置都放在init_TimeCanvas中
        self.more_settings()
        # 实例化线程
        self.work = Worker()
        self.button.clicked.connect(self.execute)

    def more_settings(self):
        # 设置窗口大小
        self.widget.resize(1000, 800)
        # 将按钮、图加入布局
        self.layout.addWidget(self.pw)
        self.layout.addWidget(self.button)
        # 设置布局
        self.layout.setContentsMargins(0, 0, 0, 0)
        # 将布局加入窗口
        self.widget.setLayout(self.layout)
        # 显示窗口
        self.widget.show()

    def execute(self):
        self.work.start()
        self.work.signal.connect(self.display)

    def display(self, x, y):
        # 将x与y加入到数组中
        self.x_data = np.append(self.x_data, x)
        self.y_data = np.append(self.y_data, y)
        # 绘图
        self.plot.setData(self.x_data, self.y_data)



class Worker(QThread):
    signal = pyqtSignal(np.ndarray, np.ndarray)

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.working = True

    def __del__(self):
        self.working = False
        self.wait()

    def run(self):
        t = np.arange(0,0.2,0.1)
        while self.working == True:
            # 绘图
            self.signal.emit(t, np.sin(t))
            t += 0.2
            # 线程休眠1秒
            self.sleep(1)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # app.processEvents()
    my_gui = TimeCanvas()
    sys.exit(app.exec_())